﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wittur.GenereateKongCoCPDF.Core.Common
{
    using System;
    using System.IO;

    public class FileLogger
    {
        // 主方法，接受一个字符串参数 msg
        public static void LogMessage(string msg)
        {
            string folderPath = CreateFolderByDate();
            string filePath = CreateFileByDate(folderPath);

            AppendMessageToFile(filePath, msg);
        }

        /// <summary>
        /// 根据当前日期和指定目录创建文件夹
        /// </summary>
        /// <param name="outPutPath"></param>
        /// <returns></returns>
        public static string CreateFolderByDateAndOutPutPath(string outPutPath)
        {
            string folderName = DateTime.Now.ToString("yyyy-MM-dd");
            string folderPath = Path.Combine(outPutPath, folderName);

            // 如果文件夹不存在，则创建
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            return folderPath;
        }

        /// <summary>
        /// 根据当前日期创建文件夹,在exe运行目录下创建文件
        /// </summary>
        /// <returns></returns>
        private static string CreateFolderByDate()
        {
            string folderName = DateTime.Now.ToString("yyyy-MM-dd");
            string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folderName);

            // 如果文件夹不存在，则创建
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            return folderPath;
        }

        // 根据当前日期创建文本文件
        private static string CreateFileByDate(string folderPath)
        {
            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            string filePath = Path.Combine(folderPath, fileName);

            // 如果文件不存在，则创建
            if (!File.Exists(filePath))
            {
                File.Create(filePath).Dispose(); // 创建文件并释放文件句柄
            }

            return filePath;
        }

        // 在文本文件中追加内容
        private static void AppendMessageToFile(string filePath, string msg)
        {
            using (StreamWriter writer = new StreamWriter(filePath, true))
            {
                writer.WriteLine(msg);
            }
        }
    }

}
